﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Xml.Linq;
using System.IO;

namespace QueueUnlimited.API
{
    public class GenericEvent : IEquatable<GenericEvent>
    {
        public string Name { get; private set; }
        public string Content { get; private set; }

        public GenericEvent(string name, string content)
        {
            if (string.IsNullOrEmpty(name))
                throw new ArgumentNullException("name");

            Name = name;
            Content = content;
        }

        public override string ToString()
        {
            string NS = "urn:www-vecozo-com:types:events:v2";
            return
                new XDocument(new XDeclaration("1.0", "UTF-8", "yes"),
                new XElement(XName.Get("GenericEvent", NS),
                    new XElement(XName.Get("Name", NS), Name),
                    new XElement(XName.Get("Content", NS), Content))).ToString(SaveOptions.OmitDuplicateNamespaces);
        }

        public bool Equals(GenericEvent other)
        {
            return other != default(GenericEvent)
                && other.Name.Equals(Name)
                && other.Content.Equals(Content);
        }

        public override bool Equals(object obj)
        {
            return Equals(obj as GenericEvent);
        }

        public override int GetHashCode()
        {
            return Name.GetHashCode() | Content.GetHashCode();
        }

        public static GenericEvent From(string messageAsString)
        {
            string NS = "urn:www-vecozo-com:types:events:v2";
            var genericEvent = XElement.Parse(messageAsString);
            var name = genericEvent.Element(XName.Get("Name", NS)).Value;
            var content = genericEvent.Element(XName.Get("Content", NS)).Value;
            return new GenericEvent(name, content);
        }
    }
}
